#!/usr/bin/env python
import cgi
import urllib
import webapp2
import jinja2
import os

from google.appengine.ext import db
from google.appengine.api import users

jinja_environment = jinja2.Environment(
  loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) )

MAX_NEW_CARDS = 10

class Card(db.Model):
  """Models and individual language flashcard, with entries for foreign 
  language text, pronunciation text, native language text, and a reference
  to an audio file.  Each card uses 'level,' an integer to represent its 
  history of correct and incorrect guesses.  Cards are initialized with value 
  0 meaning not yet shown. The higher the value, the more successful the user's
  history, and the less frequently the card will be shown."""
  forLang = db.StringProperty(multiline = True)
  pronunciation = db.StringProperty(multiline = True)
  natLang = db.StringProperty(multiline = True)
  audio = db.StringProperty()
  level = db.IntegerProperty()
  # Will eventually add much more: time added,  example sentences + audio



class MainHandler(webapp2.RequestHandler):
  def get(self):
    template_values = {}
    template = jinja_environment.get_template('templates/index.html')  
    self.response.out.write(template.render(template_values))



class StartHandler(webapp2.RequestHandler):
  def post(self):
    createOrReview = self.request.get("createReview")

    if createOrReview == "create":
      template_values = {}
      template = jinja_environment.get_template('templates/newCard.html')
      self.response.out.write(template.render(template_values))

    else:
      template_values = {}
      template = jinja_environment.get_template('templates/cardSettings.html')
      self.response.out.write(template.render(template_values))



class SetUpHandler(webapp2.RequestHandler):
  def post(self):
    frontSettings = self.request.get_all("stimulus")
    backSettings = self.request.get_all("response")

    # Extract the next card to display:
    nextCard = db.GqlQuery("SELECT * "
                           "FROM Card "
                           "WHERE level = 0 "
                           "LIMIT 1")

    # To do: switch 'fForLang' etc., to actual values extracted from db
    fForLang = ('<span id="fForLang">%s<br /></span>' % nextCard[0].forLang if
                'forLang' in frontSettings else '')
    fPronunciation = ('<span id="fPronunciation">%s<br /></span>' 
                      % nextCard[0].pronunciation if 'pronunciation' in 
                      frontSettings else '')
    fNatLang = ('<span id="fNatLang">%s<br /></span>' % nextCard[0].natLang if
                'natLang' in frontSettings else '')
    fAudio = ("""<span>
                   <audio id="fAudio" controls="controls">
                     <source src="OGG FILE SRC" />
                     <source src="MP3 FILE SRC" />
                     Your jankity ol' browser doesn't support the audio 
                     element.
                   </audio>
                 </span><br />""" 
              if 'audio' in frontSettings else '')
    bForLang = ('<span id="bForLang">%s<br /></span>' % nextCard[0].forLang if
                'forLang' in backSettings else '')
    bPronunciation = ('<span id="bPronunciation">%s<br /></span>' 
                      % nextCard[0].pronunciation if 'pronunciation' in 
                      backSettings else '')
    bNatLang = ('<span id="bNatLang">%s<br /></span>' % nextCard[0].natLang if 
                'natLang' in backSettings else '')
    bAudio = ("""<span>                                                        
                   <audio id="fAudio" controls="controls">                     
                     <source src="OGG FILE SRC" />                            
                     <source src="MP3 FILE SRC" />                             
                     Your jankity ol' browser doesn't support the audio element
.                                                                              
                   </audio>                                                   
                 </span><br />"""
              if 'audio' in backSettings else '')

    template_values = { 'fForLang': fForLang,
                        'fPronunciation': fPronunciation,
                        'fNatLang': fNatLang,
                        'fAudio': fAudio,
                        'bForLang': bForLang,
                        'bPronunciation': bPronunciation,
                        'bNatLang': bNatLang,
                        'bAudio': bAudio }
    template = jinja_environment.get_template('templates/card.html')
    self.response.out.write(template.render(template_values))

    

class WriteHandler(webapp2.RequestHandler):
  def post(self):
    card = Card()
    card.forLang = self.request.get('forLang')
    card.pronunciation = self.request.get('pronunciation')
    card.natLang = self.request.get('natLang')
    card.level = 0
    card.put()

    template_values = {}
    template = jinja_environment.get_template('templates/newCard.html')
    self.response.out.write(template.render(template_values))



#  """In the order that the cards were created, (or from a predefined order if 
#  a stock deck), cards will be promoted from level 0 to 1, indicating the 
#  first time to be shown.  If the user gets the card correct, level is 
#  incremented--by 1 if the difficulty was so-so, by 2 if easy, if hard, level 
#  remains unchanged.  If a card is missed it gets demoted by 2 (or to a min 
#  value of 1). Within a session, once a card is promoted it is not shown again#.
#  At the end of the session, new (level = 0) cards are promoted to level = 1, 
#  such that there are a total of MAX_NEW_CARDS at level 1."""
#  def post(self):
#    difficulty = self.request.get('difficulty')
class MissedHandler(webapp2.RequestHandler):
  def post(self):
    self.response.out.write("Missed me. <em>Suckah!</em>")



class HardHandler(webapp2.RequestHandler):
  def post(self):
    self.response.out.write("So hard!")



class SoSoHandler(webapp2.RequestHandler):
  def post(self):
    self.response.out.write("Meh.")



class EasyHandler(webapp2.RequestHandler):
  def post(self):
    self.response.out.write("It's a piece of cake.")

app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/start', StartHandler),
                               ('/setup', SetUpHandler),
                               ('/write', WriteHandler),
                               ('/missed', MissedHandler),
                               ('/hard', HardHandler),
                               ('/soSo', SoSoHandler),
                               ('/easy', EasyHandler)
                               ],
                              debug=True)

def main():
  run_wsgi_app(app)

if __name__ == "__main__":
  main()
